<template>
  <el-container class="main-container full-height">
    <el-header class="main-header">
      <toolbar-panel ref="toolbarRef" :designer="designer" :settings="workspace.settings">
        <template v-for="(idx, slotName) in $slots" #[slotName]>
          <slot :name="slotName"></slot>
        </template>
      </toolbar-panel>
    </el-header>
    <el-container class="main-content">
      <el-aside class="side-panel left-panel" :style="{ width: leftAsideWidth + 'px' }">
        <widget-panel :sub-lua-list="workspace.subLuaList" :designer="designer" :config-path="configPath"
          :main-height="mainHeight" @add-sub-lua-code="addSubLuaCode" @edit-sub-lua-code="editSubLuaCode"
          @delete-sub-lua-code="deleteSubLuaCode" @delete-all-sub-lua-code="deleteAllSubLuaCode" />
      </el-aside>

      <div class="resize-line resize-line-horizontal" @mousedown="resizeMousedownHandler('left')"></div>

      <el-main>
        <el-container :style="{ height: mainHeight + 'px' }">
          <el-main class="form-widget-main">
            <el-tabs v-model="activeTabName" class="design-tabs" type="card" :style="{ height: mainHeight + 'px' }"
              @tab-add="handleTabAdd" @tab-remove="handleTabRemove" @tab-change="handleTabChange">
              <el-tab-pane label="界面" name="default" :style="{ height: designTabsScrollbarHeight + 'px' }">
                <el-scrollbar class="container-scroll-bar" :style="{ height: designTabsScrollbarHeight + 'px' }" always>
                  <el-button>新建</el-button>
                </el-scrollbar>
              </el-tab-pane>
              <el-tab-pane v-for="tab in tabList" :key="tab.id" :label="tab.name" :name="tab.id"
                :style="{ height: designTabsScrollbarHeight + 'px' }" :closable="tab.closable">
                <el-scrollbar class="container-scroll-bar" :style="{ height: designTabsScrollbarHeight + 'px' }" always>
                  <v-form-widget v-if="tab.type === 'Page'" ref="formRef" :designer="tab.designer"
                    :settings="workspace.settings"></v-form-widget>
                  <div v-else-if="tab.type === 'widget-code'" class="code-tab-container">
                    <code-editor v-model="tab.content" :mode="tab.lang" :readonly="tab.readOnly"
                      :height="designTabsScrollbarHeight - 120" @update:model-value="(val) => onCodeChange(val, tab)"></code-editor>
                  </div>
                  <code-editor v-else-if="tab.type === 'page-code'" v-model="tab.content" :mode="tab.lang" :readonly="tab.readOnly"
                    :height="designTabsScrollbarHeight" @update:model-value="(val) => onCodeChange(val, tab)"></code-editor>
                    <code-editor v-else-if="tab.type === 'sub-lua-code'" v-model="tab.content" :mode="tab.lang" :readonly="tab.readOnly"
          :height="designTabsScrollbarHeight" @update:model-value="(val) => onCodeChange(val, tab)"></code-editor>
                  <code-editor v-else v-model="tab.content" :mode="tab.lang" :readonly="tab.readOnly"
                    :height="designTabsScrollbarHeight" @update:model-value="(val) => updateMainCode(val, tab.id)"></code-editor>
                </el-scrollbar>
              </el-tab-pane>
            </el-tabs>
          </el-main>
          <div class="resize-line resize-line-horizontal" @mousedown="resizeMousedownHandler('right')"></div>
          <el-aside class="side-panel right-panel"
            :style="{ width: rightAsideWidth + 'px', height: mainHeight + 'px' }">
            <setting-panel ref="settingRef" :workspace="workspace" :designer="designer" :main-height="mainHeight" />
          </el-aside>
        </el-container>
        <div class="resize-line resize-line-vertical" style="display: none"
          @mousedown="resizeMousedownHandler('center')">
        </div>
        <debug-info ref="debugLogRef" :height="debugInfoTabsheight" style="display: none" />
      </el-main>
    </el-container>
    <el-footer class="main-footer">
      <span>{{ configPath ? configPath : '请打开工作空间' }}</span>
      <el-divider direction="vertical"></el-divider>
      <span>{{ `组件个数：${designer ? designer.widgetList.length : 0}` }}</span>
    </el-footer>

    <el-dialog v-model="showButtonEditModal" title="按钮组件设计" :show-close="true" class="widget-edit-dialog" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
      <button-edit ref="buttonEditRef" :widget="editButtonWidget" :designer="designer" :settings="workspace.settings" />
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="primary" @click="saveButtonEditModal">
            {{ i18nt('designer.hint.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showModuleEditModal" title="模块组件设计" :show-close="true" class="widget-edit-dialog" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
      <module-edit ref="moduleEditRef" :widget="editModuleWidget" :designer="designer" :settings="workspace.settings" />
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="primary" @click="saveModuleEditModal">
            {{ i18nt('designer.hint.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showSlideEditModal" title="滑页组件设计" :show-close="true" class="widget-edit-dialog" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
      <slide-edit ref="slideEditRef" :widget="editSlideWidget" :designer="designer" :settings="workspace.settings" />
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="primary" @click="saveSlideEditModal">
            {{ i18nt('designer.hint.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showCodeEditModal" title="扩展代码编辑" :show-close="true" class="code-edit-dialog" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" draggable>
      <code-editor ref="ecEditor" v-model="subLuaCode" :mode="'lua'" :readonly="false"></code-editor>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCodeEditModal = false"> 取消</el-button>
          <el-button type="primary" @click="saveSubLuaCode"> 保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>
import WidgetPanel from './widget-panel/index.vue'
import ToolbarPanel from './toolbar-panel/index.vue'
import SettingPanel from './setting-panel/index.vue'
import VFormWidget from './form-widget/index.vue'
import ButtonEdit from './button-edit/index.vue'
import ModuleEdit from './module-edit/index.vue'
import SlideEdit from './slide-edit/index.vue'
import DebugInfo from './debug-info/index.vue'
import { createDesigner } from './designer'
import { addWindowResizeHandler, copyWidgetList, deepClone, generateId } from '@/utils/util'
import { changeLocale } from '@/i18n'
import * as ELECTRON from '@/electron'
import * as EVENTS from './event'
import {
  CODE_EDITOR_LANG,
  DESIGNER_TYPE,
  MAIN_NAME,
  MAIN_UI_NAME,
  SCREEN_DEFAULT_SIZE
} from './const'

export default {
  name: 'VFormDesigner',
  componentName: 'VFormDesigner',
  components: {
    WidgetPanel,
    ToolbarPanel,
    SettingPanel,
    VFormWidget,
    ButtonEdit,
    ModuleEdit,
    SlideEdit,
    DebugInfo
  },
  provide() {
    return {
      getDesignerConfig: () => this.designerConfig
    }
  },
  props: {
    designerConfig: {
      type: Object,
      default: () => {
        return {
          formTemplates: false,
          eventCollapse: true,
          widgetNameReadonly: false,
          clearDesignerButton: true,
          previewFormButton: true,
          importJsonButton: true,
          exportJsonButton: true,
          exportCodeButton: true,
          generateSFCButton: true,
          presetCssCode: '',
          resetFormJson: false
        }
      }
    }
  },
  data() {
    return {
      // 全局剪贴板，用于在不同设计器间共享复制状态
    globalClipboard: {
      widget: null,
      timestamp: 0,
      source: null // 'main' 或 'module'
    },
      globalCopyData: null,
      lastMousePosition: { x: 0, y: 0 },
      editorScrollInfo: null,
      curLocale: '',
      tabList: [],
      activeTabName: 'default',
      fonts: [],
      images: [],
      audios: [],
      videos: [],
      workspace: {
        main: {},
        pages: [],
        settings: {},
        subLuaList: []
      },
      configPath: '',
      designer: null,
      editButtonWidget: null,
      showButtonEditModal: false,
      editModuleWidget: null,
      showModuleEditModal: false,
      editSlideWidget: null,
      showSlideEditModal: false,
      mainHeight: window.innerHeight - 64,
      leftAsideWidth: 280,
      rightAsideWidth: 230,
      designTabsHeight: window.innerHeight - 64,
      resizeType: null,
      showCodeEditModal: false,
      editSubLuaName: null,
      subLuaCode: ''
    }
  },
  computed: {
    designTabsScrollbarHeight() {
      return this.mainHeight - 55
    },
    debugInfoTabsheight() {
      return this.mainHeight - this.designTabsHeight - 10
    }
  },
  mounted() {
    document.addEventListener('mousemove', (e) => {
    this.lastMousePosition = {
      x: e.clientX,
      y: e.clientY
    };
  });
    this.setupKeyboardShortcuts();
    this.$emitter.on('open-page-code-tab', (tabData) => {
      this.openPageCodeTab(tabData)
    })
    this.$emitter.on('open-widget-code-tab', (tabData) => {
      this.openWidgetCodeTab(tabData)
    })
    this.$emitter.on(EVENTS.SAVE_ALL_CODE_TABS, (options) => {
    // 同步执行保存
    this.saveAllUnsavedCodeTabs(() => {
      // 保存完成后再执行回调
      options?.callback?.();
    });
  });
    
    this.initLocale()

    this.mainHeight = window.innerHeight - 64
    addWindowResizeHandler(() => {
      this.$nextTick(() => {
        this.mainHeight = window.innerHeight - 64
      })
    })

    this.$emitter.on(ELECTRON.NEW_PROJECT, () => {
      this.$refs.toolbarRef.newProject()
    })

    this.$emitter.on(ELECTRON.OPEN_WORKSPACE_SETTINGS, () => {
      this.$emitter.emit(EVENTS.OPEN_SETTING)
    })

    this.$emitter.on(EVENTS.OPEN_SETTING, () => {
      if (!this.configPath) {
        this.$message.error('请先创建/打开项目')
        return
      }
      this.$refs.toolbarRef.openSettingModal(false)
    })

    this.$emitter.on(EVENTS.SAVE_SETTING, (settings) => {
      this.workspace.settings = {
        ...this.workspace.settings,
        ...settings
      }
      this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
    })

    this.$emitter.on(ELECTRON.WORKSPACE_CHANGE, (path) => {
      this.configPath = path
    })

    this.$emitter.on(ELECTRON.WORKSPACE_CONFIG_CHANGE, (path) => {
      if (path.indexOf('.json') > -1) {
        this.$emitter.emit(ELECTRON.LOAD_WORKSPACE_CONFIG, path)
      } else {
        console.log('工作空间配置文件错误，应该为.json文件')
      }
    })

    this.$emitter.on(ELECTRON.WORKSPACE_CONFIG_LOAD_COMPLETE, ({ filePath, workspace }) => {
      this.configPath = filePath
      this.tabList = []
      this.activeTabName = 'default'
      this.designer = null
      this.workspace.main = {}
      this.workspace.settings = {}
      this.workspace.pages = []
      this.workspace.subLuaList = []

      const { main = {}, settings = {}, pages = [], subLuaList = [] } = workspace

      this.workspace.main.name = main.name || MAIN_NAME
      this.workspace.main.id =
        this.workspace.main.id || this.workspace.main.name + generateId() + ''
      this.workspace.main.type = main.type || DESIGNER_TYPE.CODE
      this.workspace.main.lang = main.lang || CODE_EDITOR_LANG.LUA
      this.workspace.main.content = main.content || 'function on_systick_main()--定时器\r\nend\r\n'
      this.workspace.main.readOnly = main.readOnly || false

      this.workspace.settings.projectPath = settings.projectPath || ''
      this.workspace.settings.width = settings.width || SCREEN_DEFAULT_SIZE.WIDTH
      this.workspace.settings.height = settings.height || SCREEN_DEFAULT_SIZE.HEIGHT
      this.workspace.settings.scale = settings.scale || 100
      this.workspace.settings.screenOrientation =
        settings.screenOrientation || SCREEN_DEFAULT_SIZE.ORIENTATION
      this.workspace.settings.serialPort = settings.serialPort || 0
      this.workspace.settings.baudRate = settings.baudRate || 115200
      this.workspace.settings.languages = settings.languages || []

      this.workspace.subLuaList = subLuaList || []

      if (pages.length === 0) {
        this.workspace.pages.push(this.createPageDesigner(MAIN_UI_NAME))
      } else {
        pages.forEach((pageJson) => {
          this.workspace.pages.push(this.createPageDesigner(pageJson.options.name, pageJson))
        })
      }

      const mainUiPage = this.workspace.pages.find((page) => page.options.name === MAIN_UI_NAME)
      if (mainUiPage) {
        this.openPageTab(mainUiPage)
      }
    })

    this.$emitter.on(EVENTS.OPEN_CODE_EDITOR, () => {
      this.openCodeTab(this.workspace.main)
    })

    this.$emitter.on(EVENTS.TOOLBAR_SAVE_CLICK, () => {
      if (!this.workspace) {
        this.$message.error('请先打开项目')
        return
      }

      let { pages, main, settings, subLuaList} = this.workspace

      pages = this.workspace.pages
        .filter((page) => page)
        .map(({ id, type, lastId, lastUserId, options, widgetList }) => {
          return {
            id,
            type,
            lastId,
            lastUserId,
            options: deepClone(options),
            widgetList: deepClone(widgetList)
          }
        })

      this.$emitter.emit(ELECTRON.SAVE_WORKSPACE_CONFIG, {
        main: JSON.parse(JSON.stringify(main)),
        pages,
        settings: JSON.parse(JSON.stringify(settings)),
        subLuaList: JSON.parse(JSON.stringify(subLuaList))
      })
    })

    this.$emitter.on(EVENTS.NEW_PAGE, () => {
      if (!this.configPath) {
        this.$message.error('请先打开项目')
        return
      }
      let pageName = this.getPageName()
      const pageDesigner = this.createPageDesigner(pageName)
      this.workspace.pages.push(pageDesigner)
      this.openPageTab(pageDesigner)
    })

    this.$emitter.on(EVENTS.ACTIVATE_PAGE_TAB, (page) => {
      this.openPageTab(page)
    })

    this.$emitter.on(EVENTS.DELETE_PAGE, (page) => {
      if (page.options.name === MAIN_UI_NAME) {
        this.$message.error('main_ui页面不允许删除')
        return
      }

      const index = this.workspace.pages.findIndex((p) => p.id === page.id)
      const nextPage = this.workspace.pages[index + 1] || this.workspace.pages[index - 1]

      this.workspace.pages.splice(index, 1)
      this.handleTabRemove(page.id)
      this.openPageTab(nextPage)
    })

    this.$emitter.on(EVENTS.INSERT_PAGE, (page) => {
      const index = this.workspace.pages.findIndex((i) => i.id === page.id)
      let pageName = this.getPageName()
      const pageDesigner = this.createPageDesigner(pageName)
      if (index === 0) {
        this.workspace.pages.unshift(pageDesigner)
      } else {
        this.workspace.pages.splice(index, 0, pageDesigner)
      }

      this.openPageTab(pageDesigner)
    })

    this.$emitter.on(EVENTS.MOVE_UP_PAGE, (page) => {
      const index = this.workspace.pages.findIndex((item) => item.id === page.id)
      if (index === 0) {
        return
      }
      const prePage = this.workspace.pages[index - 1]
      this.workspace.pages[index - 1] = this.workspace.pages[index]
      this.workspace.pages[index] = prePage

      this.openPageTab(page)
    })

    this.$emitter.on(EVENTS.MOVE_DOWN_PAGE, (page) => {
      const index = this.workspace.pages.findIndex((item) => item.id === page.id)
      if (index === this.workspace.pages.length - 1) {
        return
      }
      const nextPage = this.workspace.pages[index + 1]
      this.workspace.pages[index + 1] = this.workspace.pages[index]
      this.workspace.pages[index] = nextPage

      this.openPageTab(page)
    })

    this.$emitter.on(EVENTS.COPY_PAGE, (page) => {
      const { id, type, lastId, lastUserId, widgetList, options } = page
      const copyPage = {
        id,
        type,
        lastId,
        lastUserId,
        options: deepClone(options),
        widgetList: copyWidgetList(deepClone(widgetList))
      }
      copyPage.id = DESIGNER_TYPE.UI + generateId() + ''
      copyPage.options.name = this.getPageName()
      this.workspace.pages.push(this.createPageDesigner(copyPage.options.name, copyPage))
    })

    this.$emitter.on(EVENTS.DELETE_ALL_PAGE, () => {
      this.workspace.pages = this.workspace.pages.filter(
        (item) => item.options.name === MAIN_UI_NAME
      )
      this.tabList = this.tabList.filter((item) => item.name === MAIN_UI_NAME)
      this.openPageTab(this.workspace.pages[0])
    })

    this.$emitter.on(EVENTS.CHANGE_TAB_LABEL, (page) => {
      const targetTab = this.findTabById(page.id)
      if (targetTab) {
        targetTab.name = page.options.name
      }
    })

    this.$emitter.on(ELECTRON.PRINT_DEBUG_LOG, (log) => {
      console.log(log)
    })

    document.addEventListener('mousemove', this.resizeMousemoveHandler)
    document.addEventListener('mouseup', this.resizeMouseupHandler)
  },
  unmounted() {
    document.removeEventListener('keydown', this.handleKeyDown);
    document.removeEventListener('mousemove', this.resizeMousemoveHandler)
    document.removeEventListener('mouseup', this.resizeMouseupHandler)
  },
  methods: {
    getCurrentDesigner() {
    const activeTab = this.findTabById(this.activeTabName);
    if (activeTab && activeTab.type === DESIGNER_TYPE.UI) {
      return activeTab.designer;
    }
    return null;
  },
  validateDesignerState() {
  const currentDesigner = this.getCurrentDesigner();
  if (!currentDesigner) return false;
  
  // 检查关键方法是否存在
  const requiredMethods = ['copySelectedWidget', 'pasteWidget', 'setSelected'];
  for (const method of requiredMethods) {
    if (typeof currentDesigner[method] !== 'function') {
      console.error(`Designer method ${method} is missing or not a function`);
      return false;
    }
  }
  
  return true;
},
  
  setupKeyboardShortcuts() {
  document.addEventListener('keydown', (event) => {
    const currentDesigner = this.getCurrentDesigner();
    if (!currentDesigner || !this.validateDesignerState()) return;
    if (!currentDesigner) return;
    
    // 检查是否在代码编辑区
    const activeElement = document.activeElement;
    const isInCodeEditor = activeElement.tagName === 'TEXTAREA' ||
      activeElement.tagName === 'INPUT' ||
      activeElement.isContentEditable;

    if (isInCodeEditor) return;

    // 检查 Ctrl 键
    if (event.ctrlKey || event.metaKey) {
      // 获取当前选中的组件
      const selectedWidget = currentDesigner.selectedWidget;
      
      // 检查是否是滑页组件或其子组件
      const isSlideWidget = selectedWidget && 
                          (selectedWidget.type === 'slidePage' || 
                          (selectedWidget.parentWidget && 
                          selectedWidget.parentWidget.type === 'slidePage'));

      switch (event.key.toLowerCase()) {
        // 修改setupKeyboardShortcuts方法中的Ctrl+C部分
case 'c':
  event.preventDefault();
  if (selectedWidget && currentDesigner.copySelectedWidget) {
    // if (isSlideWidget) {
    //   this.$refs.toolbarRef.$refs.formRef.handleSlideCopy();
    // } else {
      // 存储到全局剪贴板
      this.globalClipboard = {
        widget: deepClone(selectedWidget),
        timestamp: Date.now(),
        source: 'main' // 标记来源为主设计器
      };
      
      // 同时保存到当前设计器的剪贴板
      if (typeof currentDesigner.copySelectedWidget === 'function') {
        currentDesigner.copySelectedWidget(selectedWidget);
      //}
      this.$message.success('复制成功');
    }
  } else {
    this.$message.error('请先选择组件');
  }
  break;
          
        // 修改 setupKeyboardShortcuts 方法中的 Ctrl+V 部分
// 修改setupKeyboardShortcuts方法中的Ctrl+V部分
// 修改setupKeyboardShortcuts方法中的Ctrl+V部分
case 'v':
  event.preventDefault();
  
  // 检查当前是否在模块编辑器中
  const activeTab = this.findTabById(this.activeTabName);
  const isInModuleEditor = activeTab && activeTab.type === DESIGNER_TYPE.UI && 
                          this.designer?.editedWidget?.type === 'module';
  
  // 检查当前是否在按钮编辑器中
  const isInButtonEditor = activeTab && activeTab.type === DESIGNER_TYPE.UI && 
                           this.designer?.editedWidget?.type === 'button';
  
  // 检查当前是否在滑页编辑器中
  const isInSlideEditor = activeTab && activeTab.type === DESIGNER_TYPE.UI && 
                          this.designer?.editedWidget?.type === 'slidePage';
  
  // 如果在模块编辑器中，让模块自己处理粘贴
  if (isInModuleEditor) {
    // 获取模块编辑器的引用
    const moduleEditRef = this.$refs.moduleEditRef;
    if (moduleEditRef && moduleEditRef.pasteWidgetInModule) {
      moduleEditRef.pasteWidgetInModule(this.lastMousePosition);
    } else {
      // 备用方案：通过designer调用
      this.designer.pasteWidget(this.lastMousePosition);
    }
    break;
  }
  
  // 如果在按钮编辑器中，让按钮自己处理粘贴
  if (isInButtonEditor) {
    // 获取按钮编辑器的引用
    const buttonEditRef = this.$refs.buttonEditRef;
    if (buttonEditRef && buttonEditRef.pasteWidget) {
      buttonEditRef.pasteWidget(this.lastMousePosition);
    } else {
      // 备用方案：通过designer调用
      this.designer.pasteWidget(this.lastMousePosition);
    }
    break;
  }
  
  // 如果在滑页编辑器中，让滑页自己处理粘贴
  if (isInSlideEditor) {
    // 获取滑页编辑器的引用
    const slideEditRef = this.$refs.slideEditRef;
    if (slideEditRef && slideEditRef.pasteWidget) {
      slideEditRef.pasteWidget(this.lastMousePosition);
    } else {
      // 备用方案：通过designer调用
      this.designer.pasteWidget(this.lastMousePosition);
    }
    break;
  }
  
  // 优先使用全局剪贴板
  if (this.globalClipboard.widget) {
    const targetDesigner = currentDesigner;
    const copiedWidget = this.globalClipboard.widget;
    
    // 检查当前是否选中了模块组件
    const selectedWidget = targetDesigner.selectedWidget;
    const isPastingIntoModule = selectedWidget && selectedWidget.type === 'module';
    
    // 检查当前是否选中了按钮组件
    const isPastingIntoButton = selectedWidget && selectedWidget.type === 'button';
    
    // 检查当前是否选中了滑页组件
    const isPastingIntoSlide = selectedWidget && selectedWidget.type === 'slidePage';
    
    // 创建新的组件实例
    const newWidget = deepClone(copiedWidget);
    const tempId = generateId();
    newWidget.id = newWidget.type.replace(/-/g, '') + tempId;
    
    const lastId = targetDesigner.getLastId();
    newWidget.options.id = lastId;
    newWidget.options.name = `${newWidget.type}${lastId}`;
    
    if (newWidget.options.userId) {
      newWidget.options.userId = targetDesigner.getLastUserId();
    }
    
    // 处理子组件
    if (newWidget.widgetList) {
      this.copyWidgetListForNewPage(newWidget.widgetList, targetDesigner, newWidget);
    }
    
    // 获取画布信息
    const canvasRect = targetDesigner.formWidget?.widgetCanvasRef?.getBoundingClientRect();
    const canvasWidth = targetDesigner.formWidget?.widgetCanvasRef?.offsetWidth || targetDesigner.size.width;
    const canvasHeight = targetDesigner.formWidget?.widgetCanvasRef?.offsetHeight || targetDesigner.size.height;
    const widgetWidth = newWidget.options.width || 100;
    const widgetHeight = newWidget.options.height || 100;
    const scale = targetDesigner.formWidget?.scale || 1;
    
    // 计算粘贴位置
    let x = 50, y = 50; // 默认位置
    
    if (canvasRect) {
      // 计算相对于画布的坐标
      x = this.lastMousePosition.x - canvasRect.left;
      y = this.lastMousePosition.y - canvasRect.top;
      
      // 转换为设计器坐标
      x = Math.round(x / scale);
      y = Math.round(y / scale);
      
      // 确保组件不会超出画布边界
      x = Math.max(0, Math.min(x, canvasWidth - widgetWidth));
      y = Math.max(0, Math.min(y, canvasHeight - widgetHeight));
      
      // 如果鼠标在画布外，则使用默认位置
      if (this.lastMousePosition.x < canvasRect.left || 
          this.lastMousePosition.x > canvasRect.right || 
          this.lastMousePosition.y < canvasRect.top || 
          this.lastMousePosition.y > canvasRect.bottom) {
        x = Math.max(0, (canvasWidth - widgetWidth) / 2);
        y = Math.max(0, (canvasHeight - widgetHeight) / 2);
      }
    }
    
    newWidget.options.x = x;
    newWidget.options.y = y;
    
    // 添加到目标位置
    if (isPastingIntoModule) {
      // 如果当前选中了模块，则粘贴到模块内部
      selectedWidget.widgetList.push(newWidget);
      // 设置父模块信息
      newWidget.options.parentId = selectedWidget.id;
      newWidget.options.baseId = selectedWidget.options.id;
    } else if (isPastingIntoButton) {
      // 如果当前选中了按钮，则粘贴到按钮内部
      selectedWidget.widgetList.push(newWidget);
      // 设置父按钮信息
      newWidget.options.parentId = selectedWidget.id;
      newWidget.options.baseId = selectedWidget.options.id;
    } else if (isPastingIntoSlide) {
      // 如果当前选中了滑页，则粘贴到滑页内部
      selectedWidget.widgetList.push(newWidget);
      // 设置父滑页信息
      newWidget.options.parentId = selectedWidget.id;
      newWidget.options.baseId = selectedWidget.options.id;
    } else {
      // 否则粘贴到页面级别
      targetDesigner.widgetList.push(newWidget);
    }
    
    targetDesigner.setSelected(newWidget);
    targetDesigner.emitHistoryChange();
    
    this.$message.success('粘贴成功');
  } else {
    this.$message.error('请先复制组件');
  }
  break;
      }
    }
  });
},
copyWidgetListForNewPage(widgetList, targetDesigner, parentWidget = null) {
  widgetList.forEach((widget) => {
    const tempId = generateId();
    widget.id = widget.type.replace(/-/g, '') + tempId;
    
    const lastId = targetDesigner.getLastId();
    widget.options.id = lastId;
    widget.options.name = `${widget.type}${lastId}`;
    
    if (widget.options.userId) {
      widget.options.userId = targetDesigner.getLastUserId();
    }
    
    // 如果指定了父组件，设置父子关系
    if (parentWidget) {
      widget.options.parentId = parentWidget.id;
      widget.options.baseId = parentWidget.options.id;
    }
    
    if (widget.widgetList) {
      this.copyWidgetListForNewPage(widget.widgetList, targetDesigner, widget);
    }
  });
},
    saveAllUnsavedCodeTabs(callback) {
  // 强制同步更新所有待保存标签页
  this.tabList.forEach(tab => {
    if (tab.hasUnsavedChanges && 
        (tab.type === 'page-code' || tab.type === 'widget-code' || tab.type === 'sub-lua-code')) {
      // 立即更新到内存
      if (tab.type === 'page-code') {
        const page = this.workspace.pages.find(p => p.id === tab.pageId);
        if (page) page.options.code = tab.content;
      } else if (tab.type === 'widget-code') {
        const widget = this.findWidgetInPages(tab.widgetId);
        if (widget) widget.options[tab.eventName] = tab.content;
      } else if (tab.type === 'sub-lua-code') {
        const subLua = this.workspace.subLuaList.find(item => item.name === tab.subLuaName);
        if (subLua) {
          subLua.code = tab.content;
        } else {
          this.workspace.subLuaList.push({
            name: tab.subLuaName,
            code: tab.content
          });
        }
      }
      tab.hasUnsavedChanges = false; // 立即清除标记
    }
  });

  // 强制同步保存到文件
  this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK); 

  // 执行回调（仿真操作）
  callback?.();
},
    saveTabContent(tab) {
    if (tab.type === 'page-code') {
      const page = this.workspace.pages.find(p => p.id === tab.pageId);
      if (page) {
        page.options.code = tab.content;
      }
    } else if (tab.type === 'widget-code') {
      const widget = this.findWidgetInPages(tab.widgetId);
      if (widget) {
        widget.options[tab.eventName] = tab.content;
      }
    }
    tab.hasUnsavedChanges = false;
  },
    onCodeChange(val, tab) {
    tab.content = val;
    
    // 立即标记为"需要保存"，不等待下次检查
    tab.hasUnsavedChanges = true; 
    
    // 只有系统代码实时保存
    if (tab.id === this.workspace.main.id) {
      this.updateMainCode(val, tab.id);
    }
  },
    openWidgetCodeTab(tabData) {
      let tab = this.findTabById(`widget-code-${tabData.widgetId}-${tabData.eventName}`)
      if (!tab) {
        tab = {
          id: `widget-code-${tabData.widgetId}-${tabData.eventName}`,
          name: `${tabData.name}代码`,
          type: 'widget-code',
          content: tabData.content,
          widgetId: tabData.widgetId,
          eventName: tabData.eventName,
          closable: true,
          lang: 'lua',
          hasUnsavedChanges: false
        }
        this.tabList.push(tab)
      } else {
        tab.content = tabData.content
      }

      this.showTab(tab)
    },
    openPageCodeTab(tabData) {
      let tab = this.findTabById(`page-code-${tabData.id}`)
      if (!tab) {
        tab = {
          id: `page-code-${tabData.id}`,
          name: `${tabData.name}代码`,
          type: 'page-code',
          content: tabData.content,
          pageId: tabData.id,
          closable: true,
          lang: 'lua',
          hasUnsavedChanges: false
        }
        this.tabList.push(tab)
      } else {
        tab.content = tabData.content
      }

      this.showTab(tab)
    },
    findTabById(id) {
      return this.tabList.find((item) => item.id === id)
    },
    openCodeTab(code) {
      let tab = this.findTabById(code.id)
      if (!tab) {
        tab = {
          ...code,
          closable: true,
          hasUnsavedChanges: false
        }
        this.tabList.push(tab)
      }

      this.showTab(tab)
    },
    openPageTab(page) {
      let tab = this.findTabById(page.id)
      if (!tab) {
        tab = {
          id: page.id,
          name: page.options.name,
          type: page.type,
          designer: page,
          closable: page.options.name !== MAIN_UI_NAME,
          hasUnsavedChanges: false
        }
        this.tabList.push(tab)
      }

      this.showTab(tab)
    },
    showTab(tab) {
      if (tab.type === DESIGNER_TYPE.UI) {
        this.designer = tab.designer
      }
      this.$nextTick(() => {
        this.activeTabName = tab.id
        this.$refs.settingRef.setCurrentKey(tab.id)
      })
    },
    resizeMousedownHandler(type) {
      this.resizeType = type
    },
    resizeMouseupHandler() {
      this.resizeType = null
    },
    resizeMousemoveHandler(e) {
      if (this.resizeType === 'left') {
        this.leftAsideWidth = Math.floor(this.leftAsideWidth + e.movementX)
        if (this.leftAsideWidth < 170) {
          this.leftAsideWidth = 170
        } else if (this.leftAsideWidth > 400) {
          this.leftAsideWidth = 400
        }
      } else if (this.resizeType === 'right') {
        this.rightAsideWidth = Math.floor(this.rightAsideWidth - e.movementX)
        if (this.rightAsideWidth < 170) {
          this.rightAsideWidth = 170
        } else if (this.rightAsideWidth > 400) {
          this.rightAsideWidth = 400
        }
      } else if (this.resizeType === 'center') {
        this.designTabsHeight = Math.floor(this.designTabsHeight + e.movementY)
        if (this.designTabsHeight < 200) {
          this.designTabsHeight = 200
        } else if (this.designTabsHeight > this.mainHeight - 100) {
          this.designTabsHeight = this.mainHeight - 100
        }
      }
    },
    createPageDesigner(name, page) {
      const size = {
        width: this.workspace.settings.width,
        height: this.workspace.settings.height
      }
      return createDesigner(this, size, name, page)
    },
    getPageName() {
      const pageNames = this.workspace.pages.map((page) => page.options.name)
      let num = 0

      while (pageNames.includes(`${DESIGNER_TYPE.UI}${num}`)) {
        num++
      }
      return `${DESIGNER_TYPE.UI}${num}`
    },
    getDesignerByName(name) {
      return this.workspace.pages.find((page) => page.options.name === name)
    },
    handleTabAdd() {
      if (!this.workspace) {
        this.$message.error('请先打开项目')
        return
      }
      this.$emitter.emit(EVENTS.NEW_PAGE)
    },
    handleTabRemove(removeTabName) {
      const tab = this.findTabById(removeTabName)
      if (tab && tab.hasUnsavedChanges) {
        if (tab.type === 'sub-lua-code') {
          this.saveSubLuaCode(tab);
        } else if (tab.type === 'page-code' || tab.type === 'widget-code') {
          this.saveTabContent(tab);
        }
      }
      
      const tabs = this.tabList
      const index = tabs.findIndex((tab) => tab.id === removeTabName)

      if (removeTabName === this.activeTabName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          this.showTab(nextTab)
        } else {
          this.showTab({ id: 'default' })
        }
      }

      this.tabList = tabs.filter((tab) => tab.id !== removeTabName)
    },
    handleTabChange(tabName) {
      const tab = this.findTabById(tabName)
      if (tab) {
        this.showTab(tab)
      }
    },
    initLocale() {
      this.curLocale = localStorage.getItem('v_form_locale')
      this.curLocale = this.curLocale || 'zh-CN'
      changeLocale(this.curLocale)
    },
    clearDesigner() {
      this.designer.clearDesigner()
      this.designer.formWidget.clearWidgetRefList()
    },
    getWidgetRef(widgetName, showError = false) {
      return this.$refs['formRef'].getWidgetRef(widgetName, showError)
    },
    saveToJson() {
      this.saveAllUnsavedCodeTabs()
      this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
    },
    showEditModal(widget) {
      if (widget.type === 'button') {
        this.editButtonWidget = widget
        this.showButtonEditModal = true
        return
      }

      if (widget.type === 'slidePage') {
        this.editSlideWidget = widget
        this.showSlideEditModal = true
        return
      }

      this.editModuleWidget = widget
      this.showModuleEditModal = true
    },
    saveButtonEditModal() {
      if (this.designer) {
        this.designer.setSelected(this.editButtonWidget)
        this.designer.editWidget(null)
      }
      this.showButtonEditModal = false
    },
    saveModuleEditModal() {
      if (this.designer) {
        this.designer.setSelected(this.editModuleWidget)
        this.designer.editWidget(null)
      }
      this.showModuleEditModal = false
    },
    saveSlideEditModal() {
      if (this.designer) {
        this.designer.setSelected(this.editSlideWidget)
        this.designer.editWidget(null)
      }
      this.showSlideEditModal = false
    },
    updateMainCode(code, tabId) {
      this.workspace.main.content = code
      this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK)
    },
    findWidgetInPages(widgetId) {
      for (const page of this.workspace.pages) {
        const widget = this.findWidgetById(widgetId, page.widgetList)
        if (widget) return widget
      }
      return null
    },
    findWidgetById(widgetId, widgetList) {
      for (const widget of widgetList) {
        if (widget.id === widgetId) return widget
        if (widget.widgetList && widget.widgetList.length > 0) {
          const found = this.findWidgetById(widgetId, widget.widgetList)
          if (found) return found
        }
      }
      return null
    },
    addSubLuaCode() {
  const subLuaName = this.generateSubLuaName()
  const defaultCode = ``
  
  // 添加到子Lua列表
  this.workspace.subLuaList.push({
    name: subLuaName,
    code: defaultCode
  })
  
  // 打开标签页
  this.openSubLuaTab(subLuaName)
},
    generateSubLuaName() {
  let count = 1
  while (this.workspace.subLuaList.find((item) => item.name === `sub_lua_${count}`)) {
    count++
  }
  return `sub_lua_${count}`
},
openSubLuaTab(name) {
  const subLua = this.workspace.subLuaList.find(item => item.name === name)
  if (!subLua) return
  
  let tab = this.findTabById(`sub-lua-${name}`)
  if (!tab) {
    tab = {
      id: `sub-lua-${name}`,
      name: `${name}.lua`,
      type: 'sub-lua-code',
      content: subLua.code || '',
      subLuaName: name,
      closable: true,
      lang: 'lua',
      hasUnsavedChanges: false
    }
    this.tabList.push(tab)
  }
  
  this.showTab(tab)
},
    editSubLuaCode(name) {
  this.openSubLuaTab(name)
},
    saveSubLuaCode(tab) {
  if (!tab.subLuaName) return
  
  const subLua = this.workspace.subLuaList.find(item => item.name === tab.subLuaName)
  if (subLua) {
    subLua.code = tab.content
  } else {
    this.workspace.subLuaList.push({
      name: tab.subLuaName,
      code: tab.content
    })
  }
  
  tab.hasUnsavedChanges = false
  this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK, this.workspace)
},
    deleteSubLuaCode(name) {
      const deleteItemIndex = this.workspace.subLuaList.findIndex((item) => item.name === name)
      if (deleteItemIndex !== -1) {
        this.workspace.subLuaList.splice(deleteItemIndex, 1)
        this.handleTabRemove(`sub-lua-${name}`)
        this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK, this.workspace)
      }
    },
    deleteAllSubLuaCode() {
  if (this.workspace.subLuaList.length > 0) {
    // 关闭所有相关的标签页
    this.workspace.subLuaList.forEach(item => {
      this.handleTabRemove(`sub-lua-${item.name}`)
    })
    this.workspace.subLuaList = []
    this.$emitter.emit(EVENTS.TOOLBAR_SAVE_CLICK, this.workspace)
  }
}
  }
}
</script>

<style lang="scss" scoped>
.el-container.main-container {
  height: 100%;
  overflow-y: hidden;

  .el-header.main-header {
    height: 60px !important;
    min-width: 800px;
    padding: 0;
    line-height: 48px !important;
  }

  .el-container.main-content {
    height: calc(100% - 48px - 60px);

    .side-panel {
      margin: 0;
      padding: 0;
      background: inherit;
      overflow: hidden;
    }

    .el-main {
      overflow: hidden;
      padding: 0;

      .form-widget-main {
        :deep(.el-tabs__content) {
          background-color: inherit;
        }
      }
    }
  }

  .el-footer.main-footer {
    height: 32px !important;
    line-height: 32px;
    font-size: 12px;
  }
}
</style>